import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //仪器所有任务列表
    list: [],
    inputSignature: '',
    inputName: '',
    // 下一个Id
    nextId: 4
  },
  mutations: {
    initList(state, list) {
      state.list = list
    },
    // 为 store 中的 inputValue1 赋值
    setInputSignature(state, val) {
      state.inputSignature = val
    },
    // 为 store 中的 inputValue2 赋值
    setInputName(state, val) {
      state.inputName = val
    },
    // 添加列表项
    addItem(state) {
      const obj = {
        id: state.nextId,
        signature: state.inputSignature,
        name: state.inputName
      }
      state.list.push(obj)
      state.nextId++
      state.inputSignature = ''
      state.inputName = ''
    },
    // 根据Id删除对应的任务事项
    removeItem(state, id) {
      console.log(id)
      // 根据Id查找对应项的索引
      const i = state.list.findIndex((x) => x.id === id)
      // 根据索引，删除对应的元素
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    }
  },
  actions: {
    getList(context) {
      axios.get('/getlist').then(({ data: res }) => {
        // console.log(res)
        context.commit('initList', res.data)
      })
    }
  }
})
